package leetCode.offer30;

/**
 * 数组实现
 */
public class MinStackV1 implements MinStack{

    private Integer[] stack;
    private static final int DEFAULT_NUM = 10;
    private int min = Integer.MAX_VALUE;
    private int size;

    public MinStackV1(){
        stack = new Integer[DEFAULT_NUM];
    }

    @Override
    public void push(int x) {
        if(size==stack.length) resize();
        stack[size++] = x;
        if(x<min) min = x;
    }

    @Override
    public void pop() {
        int pop = stack[size-1];
        stack[--size] = null;
        if(pop==min){
            min = Integer.MAX_VALUE;
            for(Integer m:stack){
                if(m!=null){
                    if(m<min) min = m;
                }
            }
        }
    }

    @Override
    public int top() {
        return stack[size-1];
    }

    @Override
    public int min() {
        return min;
    }

    /**
     扩容
     */
    private void resize(){
        int length = stack.length;
        Integer[] newStack = new Integer[length*2];
        System.arraycopy(stack, 0, newStack, 0, length);
        stack = newStack;
    }

}
